package Util::Taobao::CreateTaobaoStores;
use Moose;
use namespace::autoclean;
use JSON;
use WWW::Curl::Easy;
use HTTP::Response;
use Digest::MD5 qw(md5_hex);
use URI::Escape;
use Encode;

sub create_store {
	my ($self, $user_id, $appKey, $clientSecret, $gatewayUrl, $redirectUri, $oauthUri, $apiVersion, $dataRef, $catModel, $leimuModel, $leimuCatModel, $commtedItemModel, $storeCreateModel, $storeSearchModel, $userStoreModel) = @_;

	my ($leimu_cid, $leimu_name, $leimu_id, $catid);
	for my $key (keys %$dataRef) {
		my $cid = $dataRef->{$key}->{'cid'};
		my $title = $dataRef->{$key}->{'title'};
		my $desc = $dataRef->{$key}->{'desc'};
		my $num_iid = $dataRef->{$key}->{'num_iid'};
		my $detail_url = $dataRef->{$key}->{'detail_url'};
		my $pic_url = $dataRef->{$key}->{'pic_url'};
		my @cats = $catModel->get_cat_by_cid($cid);

		#This category already exists in database.
		if(scalar @cats > 0) {
			$catid = $cats[0]->id;	
		} else {
			#Go to taobao to get the information for this category and its leimu and insert them to database
			my ($name, $parent_cid, $returncode) = $self->query_category_from_taobao($appKey, $clientSecret, $gatewayUrl, $redirectUri, $oauthUri, $apiVersion, $cid);
			if($parent_cid eq '0') {
				$leimu_cid = $cid;
				$leimu_name = $name;	
			} else {
				#Find the root category as the leimu
				while($parent_cid ne '0') {
					$leimu_cid = $parent_cid;
					($leimu_name, $parent_cid, $returncode) = $self->query_category_from_taobao($appKey, $clientSecret, $gatewayUrl, $redirectUri, $oauthUri, $apiVersion, $parent_cid);
					
				}
			}
			my $category = $catModel->create($cid, $name);
			$catid = $category->id;
			my @leimus = $leimuModel->get_leimu_by_cid($leimu_cid);
			if(scalar @leimus > 0) {
				$leimu_id = $leimus[0]->id;	
			} else {
				my $leimu = $leimuModel->create($leimu_cid, $leimu_name);
				$leimu_id = $leimu->id;
			}
			my $leimuCat = $leimuCatModel->create($leimu_id, $category->id);
		}
		my $commItem = $commtedItemModel->create('2');

		#source id = 1 is for taobao
		my @my_stores = $storeSearchModel->get_stores_by_numiid($num_iid);
		if(scalar @my_stores > 0) {
			my $user_store = $userStoreModel->get_owner($my_stores[0]->id);
			$user_store->update({
				user_id => $user_id
			});
			$my_stores[0]->update({
				name => $title,
				url => $detail_url,
				description => $desc,
				image => $pic_url});
		} else {
			my $store = $storeCreateModel->createTaobaoStore( $user_id, $title, $detail_url, $pic_url, "", $desc, $commItem->id, "", $catid, "1");
		}
	}
}
sub query_category_from_taobao {
	my ($self, $appKey, $clientSecret, $gatewayUrl, $redirectUri, $oauthUri, $apiVersion, $cid) = @_;

	my %sysParams;
	$sysParams{"app_key"} = $appKey;
	$sysParams{"v"} = $apiVersion;
	$sysParams{"format"} = "json";
	$sysParams{"sign_method"} = "md5";
	$sysParams{"partner_id"} = "top-apitools";
	$sysParams{"method"} = "taobao.itemcats.get";
	my $time = `date +"%Y-%m-%d %H:%M:%S"`;
	chomp($time);
	$sysParams{"timestamp"} = $time;
	$sysParams{"fields"} = "cid,parent_cid,name,is_parent";
	$sysParams{"cids"} = $cid;

	my %resData;
	my $returncode;

	my $stringToBeSigned = $clientSecret;
	foreach my $key (sort(keys(%sysParams))) {
		$stringToBeSigned .= "$key$sysParams{$key}";
	}
	$stringToBeSigned .= $clientSecret;
	my $md5 = uc(md5_hex($stringToBeSigned));
	$sysParams{"sign"} = $md5;

	my $requestUrl = $gatewayUrl . "?";
	foreach my $key (sort(keys(%sysParams))) {
		$requestUrl .= "$key=" . uri_escape($sysParams{$key}) . "&";
	}

	my $curl_new = WWW::Curl::Easy->new;
	$curl_new->setopt(CURLOPT_HEADER,1);
	$curl_new->setopt(CURLOPT_URL, $requestUrl);

	my $response_new;
	$curl_new->setopt(CURLOPT_WRITEDATA,\$response_new);
	my $retcode_new = $curl_new->perform;
	
	#TODO
	$retcode_new = 0;
	my ($name, $parent_cid);
	if ($retcode_new == 0) {
		$response_new = HTTP::Response->parse($response_new);

		my $xml_new = $response_new->decoded_content;
		my $json_new = from_json($xml_new);

		my $items = $json_new->{'itemcats_get_response'}->{'item_cats'}->{'item_cat'};
		
		$parent_cid = $items->[0]->{'parent_cid'};
		$name = $items->[0]->{'name'};
		my @names = split (/\//, $name);
		$name = $names[0];
		$returncode = 0;
	} else {
		$returncode  = 1;
	}

	return ($name, $parent_cid, $returncode);
}
__PACKAGE__->meta->make_immutable;

1;
